package com.sq.goodline.service;

import java.util.Date;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sq.goodline.controller.dto.PartnerTokenResultDto;
import com.sq.goodline.controller.dto.TransResponse;
import com.sq.goodline.dao.PartnerTokenDao;
import com.sq.goodline.dao.po.PartnerToken;
import com.sq.goodline.util.DateUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class AuthService {
	
	@Autowired
	PartnerTokenDao partnerTokenDao;
	
	/**
	 * 生成对外接口的token
	 */
	public TransResponse<PartnerTokenResultDto> genAccessToken(String partnerCode, String partnerSecret) {
		try {
			log.info("获取token服务，partnerCode:{},partnerSecret:{}",partnerCode,partnerSecret);
			PartnerToken accessToken = partnerTokenDao.selectById(partnerCode);
			if(accessToken==null || !partnerSecret.equals(accessToken.getPartnerSecret())) {
				return TransResponse.error("1003","参数错误");
			}
			
			String genToken = "TK"+UUID.randomUUID().toString().replace("-","");
			log.info("生成token:{}",genToken);
			
			Date date = new Date();
			accessToken.setToken(genToken);
			accessToken.setStartTime(date);
			accessToken.setEndTime(DateUtils.addHours(date, 2));//2小时有效
			int i = partnerTokenDao.updateById(accessToken);
			log.info("更新accessToken完成：{}",i);
			
			PartnerTokenResultDto resultDto = new PartnerTokenResultDto();
			resultDto.setAccessToken(genToken); 
			resultDto.setExpireDate(DateUtils.formatDate(accessToken.getEndTime(), "yyyy-MM-dd HH:mm:ss")); 
			return TransResponse.success(resultDto);
		}catch(Exception e) {
			log.error("生成token异常：",e);
			return TransResponse.error("生成token异常");
		}
	}
}
